package com.example.controller;

import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class Consume {

    private  static Set<String> orders = new HashSet();
    private static String substring = "1234";
//    @RabbitListener(queues = {"A"})
    public void consumeA(Channel channel, Message message,String msg)  {
//        System.out.println(orders.contains(substring));
        if(!orders.contains(substring)){
            orders.add(substring);
//            if(StringUtils.hasText(msg)){
                    log.info("A"+msg);
                    try {
//                        TimeUnit.SECONDS.sleep(5);
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//                        orders.remove(substring);
                        System.out.println("移除成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }else {
                try {
                    System.out.println("a拒绝应答");
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//        }
//        else {
//            return;
//        }
    }
//    @RabbitListener(queues = {"B"})
    public void consumeB(Channel channel, Message message,String msg) throws IOException {
        byte[] body = message.getBody();
        String s = new String(body);
        log.info("备份队列消息为{}",s);
        if(StringUtils.hasText(s)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
//    @RabbitListener(queues = {"deadQueue"})
    public void deadConsume(Channel channel, Message message,String msg) throws IOException {
        byte[] body = message.getBody();
        String s = new String(body);
        System.out.println(s);
        log.info("死信队列消息为{}",s);
        if(StringUtils.hasText(s)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
//    @RabbitListener(queues = {"out"})
    public void out(String msg,Channel channel,Message message){
        try {
            log.info(msg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
